/*
 *    Copyright (c) 2018-2025, haohanwork.com All rights reserved.
 */
package com.haohan.cloud.scm.manage.service.impl;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.haohan.cloud.scm.api.common.dto.SelfPageMapper;
import com.haohan.cloud.scm.api.constant.enums.manage.MerchantStatusEnum;
import com.haohan.cloud.scm.api.constant.enums.manage.ShopLevelEnum;
import com.haohan.cloud.scm.api.manage.dto.ShopExtDTO;
import com.haohan.cloud.scm.api.manage.dto.ShopSqlDTO;
import com.haohan.cloud.scm.api.manage.entity.Shop;
import com.haohan.cloud.scm.manage.mapper.ShopMapper;
import com.haohan.cloud.scm.manage.service.ShopService;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

/**
 * 店铺
 *
 * @author haohan
 * @date 2019-05-13 17:39:04
 */
@Service
public class ShopServiceImpl extends ServiceImpl<ShopMapper, Shop> implements ShopService {

    /**
     * 商家 pds 采购配送店铺
     *
     * @param merchantId 可为空
     * @return
     */
    @Override
    public Shop fetchPdsShop(String merchantId) {
        return baseMapper.selectList(Wrappers.<Shop>query().lambda()
                .eq(StrUtil.isNotBlank(merchantId), Shop::getMerchantId, merchantId)
                .eq(Shop::getStatus, MerchantStatusEnum.enabled)
                .eq(Shop::getShopLevel, ShopLevelEnum.pds)
                .orderByDesc(Shop::getUpdateDate)
        ).stream().findFirst().orElse(null);
    }

    /**
     * 商家 启用店铺列表
     *
     * @param merchantId
     * @return
     */
    @Override
    public List<Shop> findEnableList(String merchantId) {
        return baseMapper.selectList(Wrappers.<Shop>query().lambda()
                .eq(StrUtil.isNotBlank(merchantId), Shop::getMerchantId, merchantId)
                .eq(Shop::getStatus, MerchantStatusEnum.enabled)
                .orderByDesc(Shop::getUpdateDate)
        ).stream()
                .sorted((t1, t2) -> {
                    // 采购配送店排在前
                    if (t1.getShopLevel() == t2.getShopLevel()) {
                        return 0;
                    } else if (t1.getShopLevel() == ShopLevelEnum.pds) {
                        return -1;
                    }
                    return 0;
                })
                .collect(Collectors.toList());
    }

    /**
     * 分页查询 联查商家
     *
     * @param query
     * @return
     */
    @Override
    public IPage<ShopExtDTO> findPage(ShopSqlDTO query) {
        return SelfPageMapper.findPage(query, baseMapper);
    }
}
